package me.flyray.auth.service.impl;

import me.flyray.auth.common.bean.UserJWTInfo;
import me.flyray.auth.common.vo.JwtAuthenticationRequest;
import me.flyray.auth.common.vo.JwtAuthenticationResponse;
import me.flyray.auth.util.user.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import me.flyray.auth.service.AuthService;
import me.flyray.common.exception.auth.UserInvalidException;

import lombok.extern.slf4j.Slf4j;

/**
 * 后台登陆用户token授权实现
 * @author Administrator
 *
 */
@Slf4j
@Service
public class AuthServiceImpl implements AuthService {

	private JwtTokenUtil jwtTokenUtil;

	@Autowired
	public AuthServiceImpl(JwtTokenUtil jwtTokenUtil) {
		this.jwtTokenUtil = jwtTokenUtil;
	}

	@Override
	public JwtAuthenticationResponse getAdminUserToken(JwtAuthenticationRequest authenticationRequest) throws Exception {
		JwtAuthenticationResponse response = new JwtAuthenticationResponse();
		if (!StringUtils.isEmpty(authenticationRequest.getUserId())) {
			String token = jwtTokenUtil.generateToken(new UserJWTInfo(authenticationRequest.getPlatformId(), authenticationRequest.getUsername(), authenticationRequest.getUserId() + ""));
			response.setPlatformId(authenticationRequest.getPlatformId());
			response.setUsername(authenticationRequest.getUsername());
			response.setToken(token);
		} else {
			throw new UserInvalidException("用户不存在或账户密码错误!");
		}
		return response;
	}

	@Override
	public void validate(String token) throws Exception {
		jwtTokenUtil.getInfoFromToken(token);
	}

	@Override
	public String refresh(String oldToken) throws Exception {
		return jwtTokenUtil.generateToken(jwtTokenUtil.getInfoFromToken(oldToken));
	}

	@Override
	public JwtAuthenticationResponse getBizUserToken(JwtAuthenticationRequest authenticationRequest) throws Exception {
		JwtAuthenticationResponse response = new JwtAuthenticationResponse();
		if (!StringUtils.isEmpty(authenticationRequest.getUserId())) {
			String token = jwtTokenUtil
					.generateToken(new UserJWTInfo(authenticationRequest.getPlatformId(), authenticationRequest.getUsername(), authenticationRequest.getUserId() + ""));
			response.setPlatformId(authenticationRequest.getPlatformId());
			response.setUsername(authenticationRequest.getUsername());
			response.setToken(token);
		} else {
			throw new UserInvalidException("用户不存在或账户密码错误!");
		}
		return response;
	}

}